package tt.dz.egobus.servicemanager.cycle;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import tt.dz.egobus.servicemanager.core.exception.BusinessException;

import javax.annotation.PreDestroy;
import javax.sql.DataSource;

/**
 * @author Anson
 * @date 17-5-12
 * @name
 * @since 1.0.4
 */
@Component
public class SpringAppCycleProcessor implements AppCycleProcessor, InitializingBean {

    @Autowired
    private ApplicationContext applicationContext;

    private final AppCycleProcessorChain delegate;

    public SpringAppCycleProcessor() {
        this.delegate = new DefaultAppCycleProcessor();
    }

    public SpringAppCycleProcessor(AppCycleProcessorChain delegate) {
        this.delegate = new DefaultAppCycleProcessor();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.delegate.isProcessor()) {
            return;
        }
        this.delegate.addChain(new AppDbInitCycleProcessor(applicationContext.getBean(DataSource.class)));
        this.delegate.addChain(new AppTaskInitCycleProcessor(applicationContext));

        this.processorInit();
    }

    @Override
    public boolean isProcessor() {
        return this.delegate.isProcessor();
    }

    @Override
    public boolean processorInit() throws BusinessException {
        return this.delegate.processorInit();
    }

    @PreDestroy
    @Override
    public boolean processorDestroyed() throws BusinessException {
        return this.delegate.processorDestroyed();
    }

}
